<?php
/*
*微信事件接口
*1、进入微信服务号-基本配置-服务器配置
*/
include "../../library/openFunction.php";
include "wxFunction.php";
//echo $_GET['echostr'];//服务器配置url时返回即可配置成功
//接收微信信息推送
$xml = $GLOBALS["HTTP_RAW_POST_DATA"];
libxml_set_external_entity_loader(true);//禁止从外部加载XML实体
$wxData = xmlToArray($xml);//将接收到的xml转为数组
$wxid = $wxData['ToUserName'];//开发者微信号（微信公众号原始ID）
$wxOpenid = $wxData['FromUserName'];//当前用户微信openid
$keyword = trim($wxData['Content']);//客户输入的关键词
$EventKey = $wxData['EventKey'];//菜单点击事件预设关键词
$Event = $wxData['Event'];//事件
$TimeStamp = time();//当前时间戳
//执行
if(!empty($keyword)){//关键词回复
	$sql = mysql_query(" select * from wxKey ");
	while($array = mysql_fetch_array($sql)){
		$key = explode("，",$array['keyWord']);
		foreach($key as $k){
			if(strstr($keyword,$k) !== false){
				$text = $array['text'];
			}
		}
	}
	if(empty($text)){
		$xml = wximgWord($wxOpenid,$wxid);
	}else{
		$xml = wxWord($wxOpenid,$wxid,$text);
	}
	echo $xml;
}elseif($Event == "subscribe"){//关注
	$wxData = wxData($wxOpenid);
	//新增或更新客户基本资料
	$kehu = query("kehu"," wxOpenid = '$wxOpenid' ");
	if(empty($kehu['khid'])){
		//生成客户ID号
		$khid = rand(1000000000,9999999999);
		while(mysql_num_rows(mysql_query(" select * from kehu where khid = '$khid' ")) > 0){
			$khid = rand(1000000000,9999999999);
		}
		//插入数据库
		mysql_query(" insert into kehu (khid,Source,wxOpenid,wxSex,wxNickName,wxAddress,wxIco,wxFollow,updateTime,time)
		values ('$khid','微信自动注册','$wxOpenid','$wxData[sex]','$wxData[nickname]','$wxData[address]','$wxData[ico]','是','$time','$time') ");
	}else{
		mysql_query(" update kehu set
		wxSex = '$wxData[sex]',
		wxNickName = '$wxData[nickname]',
		wxAddress = '$wxData[address]',
		wxIco = '$wxData[ico]',
		wxFollow = '是',
		updateTime = '$time' where wxOpenid = '$wxOpenid' ");
	}
	//检查此人是不是员工身份
	$admin = query("admin"," wxOpenid = '$wxOpenid' ");
	if(!empty($admin['wxOpenid'])){
		mysql_query(" update admin set
		wxSex = '$wxData[sex]',
		wxNickName = '$wxData[nickname]',
		wxAddress = '$wxData[address]',
		wxIco = '$wxData[ico]',
		wxFollow = '是',
		updateTime = '$time' where wxOpenid = '$wxOpenid' ");
	}
	//推送图文消息
	$xml = wximgWord($wxOpenid,$wxid);
	echo $xml;
}elseif($Event == "unsubscribe"){//取消关注
	//检查此人是不是员工身份
	$admin = query("admin"," wxOpenid = '$wxOpenid' ");
	if(!empty($admin['wxOpenid'])){
		mysql_query(" update admin set
		wxFollow = '否',
		updateTime = '$time' where wxOpenid = '$wxOpenid' ");
	}
	//检查此人是不是客户身份
	$kehu = query("kehu"," wxOpenid = '$wxOpenid' ");
	if(!empty($kehu['wxOpenid'])){
		mysql_query(" update kehu set
		wxFollow = '否',
		updateTime = '$time' where wxOpenid = '$wxOpenid' ");
	}
}else{
	$text = "您好，欢迎光临雨木科技。";
	$xml = wxWord($wxOpenid,$wxid,$text);
	echo $xml;
}
?>
